package com.elf.reactnative;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import java.io.File;

import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread;

public class ReactFragment extends Fragment {

    private ReactNativeDelegate mDelegate;
    private ReactAppInfo mReactAppInfo;
    private boolean loaded=false;

    public void createReactFragmentDelegate(Activity activity, ReactAppInfo reactAppInfo,String mainComponentName) {
        mReactAppInfo = reactAppInfo;
        String jsFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
                + File.separator + reactAppInfo.id + "_" + reactAppInfo.version + ".bundle";

        mDelegate = new ReactNativeDelegate(activity, jsFile, mainComponentName);
        mDelegate.getReactInstanceManager();
    }

    public ReactNativeDelegate getReactFragmentDelegate(){
        return mDelegate;
    }

    public ReactAppInfo getReactAppInfo() {
        return mReactAppInfo;
    }

    public boolean isLoaded() {
        return loaded;
    }

    public void loaded() {
        loaded = true;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        return mDelegate.createRootView();
    }

    @Override
    public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        String jsFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
                + File.separator + mReactAppInfo.id + "_" + mReactAppInfo.version + ".bundle";

        FileDownload.download(mReactAppInfo.url, jsFile, new FileDownload.DownloadListener() {
            @Override
            public void success(final String fileName) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mDelegate.onCreate(savedInstanceState);
                    }
                });
            }

            @Override
            public void fail(final String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showMsg(msg);
                    }
                });
            }
        });
    }

    private void showMsg(String text){
        Toast.makeText(getContext(),text,Toast.LENGTH_SHORT).show();
    }


}
